﻿//服务器两端用户的交互命令
var eCmd_RequestControl = 10;
var eCmd_AnswerControlRequest = 11;
var eCmd_RejectControlRequest = 12;
var eCmd_StopControl = 13;
var eCmd_StopControlForLocalFailed = 14;
var eCmd_StartingRemoteControl = 15;
var eCmd_StartedRemoteControl = 16;

//远程交互时需要的信息
var checkStatusInterval = -1;
var checkOfflineTimes = 0;
var echoLoopId = null;
var checkLoopId = null;
var myuserid = '';
var remotingPeerId = '';
var socket = null;

var isControlFirstFailed = true;

//初始化InitImRemote
function InitImRemote()
{
	if(remoteControl != null)
	{
		return;
	}
	remoteControl = new NiuniuRemoteControl();
	remoteControl.PluginLoaded = OnPluginLoadedCallback;
	remoteControl.PluginUnload = OnPluginUnload;
	remoteControl.doShowDownload = ShowDownload;
	remoteControl.OnControlNotice = OnControlNotice;	
	remoteControl.Init();
}

function appendInfo(info)
{
	$("#recvcontent").append("<br/><span>" + info + "</span>");
}

function StartEngine()
{
	remoteControl.StartEngine();
}

function AcceptAfterInstallIfNeed()
{
	if(remoteControl.isUseful() && socket != null)
	{
		var lastUnFinishedPeerId = getCookie("lastUnFinishedPeerId");
		if(lastUnFinishedPeerId != "")
		{
			setCookie("lastUnFinishedPeerId", "");
			socket.emit("command", {type: eCmd_StartedRemoteControl, peerid:myuserid, userid:lastUnFinishedPeerId});
			socket.emit("command", {type: eCmd_AnswerControlRequest, peerid:myuserid, userid:lastUnFinishedPeerId});
			var ret = remoteControl.InitRemote($("#myid").val(), lastUnFinishedPeerId, "孙悟空", "牛魔王");
			if(ret == emcontrolSuccess)
			{	
				clearInterval(checkStatusInterval);			
				checkStatusInterval = setInterval("GetStatus();", 1000);
			}
			remoteControl.StartControl(0, 0, 0);								
			appendInfo("正在启动远程服务.");
			remotingPeerId = lastUnFinishedPeerId;
			startOrStopCheckLoop(true);
		}
	}
}

function ShowStartOrdownload(info)
{
	if(remoteControl.base.IsNeedCustomizedProtocol())
	{
		StartEngine();
		ShowDownload(false);		
	}
	else
	{
		ShowDownload(true);
	}
	
}

function ShowDownload(forceDownload)
{
	if(!forceDownload)
	{
		$('#controlstate').html('如果超过5秒无响应，请点此<a target="_blank" href="' + remoteControl.downloadUrl + '">安装</a>');
	}
	else{
		$('#controlstate').html('控件加载失败，你需要安装插件并启动，点此<a target="_blank" href="' + remoteControl.downloadUrl + '">安装</a>');
	}
}

function OnControlNotice(obj)
{
	$("#recvcontent").append("<br/><span>" + obj.param + "</span>");
}
	
function OnPluginUnload()
{
	clearInterval(checkStatusInterval);	
	$('#controlstate').html('控件连接断开，请<a onclick="StartEngine();" href="javascript:void(0);">点此启动</a>');
	$('#status').html("控件连接断开。");
	if(socket != null)
	{
		socket.emit("command", {type: eCmd_StopControlForLocalFailed, peerid:myuserid, userid:remotingPeerId});
	}
}

function OnPluginLoadedCallback(success)
{
	if(success)
	{
		//隐藏部分弹出的安装下载提示信息 
		$('#status').html("");
		$('#controlstate').html('远程组件加载成功.');			
		$("#myid").val(myuserid);		
		setTimeout("GetVersion();", 300);
		AcceptAfterInstallIfNeed();
	}
	else
	{
		//$('#controlstate').html('远程组件加载失败，<a onclick="StartEngine();" href="javascript:void(0);">点此启动</a>');
	}
}


function GetStatus()
{
	remoteControl.GetStatus( function(obj){
		var nStatus = obj.retValue;		
		var LIMIT_VALUE_STATUS = 100000;
		var connectStatus = parseInt(nStatus / LIMIT_VALUE_STATUS);
		var remoteStatus = parseInt(nStatus % LIMIT_VALUE_STATUS);
		var statusInfo = "连接状态：" + remoteControl.GetConnectStatusString(connectStatus) + "，远程状态：" + remoteControl.GetRemoteStatusString(remoteStatus);
		$('#status').html(statusInfo);
	} );
}

function GetVersion()
{
	remoteControl.GetVersion( function(obj){
		var verObj = eval("(" + obj.param + ")");
		//可以在此根据最新的版本号与控件返回的版本号对比，决定是否要提示升级  
		$('#versioninfo').html("控件版本号：" + verObj.version);		
	} );
}
	
function loopEcho()
{
	try
	{
		//console.log("loopEcho");
	}
	catch(e){}
	if(socket == null)
	{
		return;
	}
	socket.emit("echo", {userid:myuserid});
}

//远程过程中检查对方是否已经掉线 
function startOrStopCheckLoop(isStart)
{
	if(!isStart)
	{
		if(checkLoopId != null)
		{
			clearInterval(checkLoopId);
			checkLoopId = null;
		}
		checkOfflineTimes = 0;
		remotingPeerId = '';
	}
	else
	{
		checkLoopId = setInterval("doCheck();", 2000);
	}
}

function doCheck()
{
	if(socket != null)
	{
		socket.emit("check", {userid:remotingPeerId});
	}
}
	

function connectServer()
{
	socket=io.connect('ggniu.cn:8888');	
	socket.on('connect', function () {
		appendInfo("接连服务器成功.");
	});
	//接收来自服务端的信息事件
	socket.on('callback',function(msg)
	{
		//alert(msg);
		if(msg.type == 'reg')
		{
			myuserid = msg.userid;
			$("#myid").val(msg.userid);
			setCookie("myuserid", msg.userid);
			
			$('#controlstate').html('登录服务器成功，请输入对方ID进行远程，或告知对方您的ID以便对方可远程您的电脑。');
			appendInfo("登录成功.");
			if(echoLoopId != null)
			{
				clearInterval(echoLoopId);
			}
			echoLoopId = setInterval('loopEcho();', 1000);
		}
		else if(msg.type == 'connect')
		{
			socket.emit('reg', {userid:myuserid});
		}
		else if(msg.type == 'check')
		{
			if(!msg.exist)
			{
				checkOfflineTimes++;
				if(checkOfflineTimes > 3)
				{
					startOrStopCheckLoop(false);
					appendInfo("对方已经退出，结束远程.");
					remoteControl.DisConnect();
				}
			}
		}
		else if(msg.type == "echo")
		{
			try
			{
				//console.log("received echo ret.");
			}
			catch(e){}
		}
		else if(msg.type == 'command')
		{
			if(!msg.result)
			{
				appendInfo("命令发送失败，对方不在线.");
			}
		}
	});
	
	socket.on('command',function(msg){
		switch(msg.type)
		{
			case eCmd_RequestControl:
			{
				appendInfo("收到远程连接请求.");
				var peerid = msg.peerid;
				var peername = msg.peername;
				//弹出选择窗口
				if(!confirm(peername+" 想要控制你的电脑，接受么？"))
				{
					socket.emit("command", {type: eCmd_RejectControlRequest, peerid:myuserid, peername:"牛魔王", userid:peerid});
					appendInfo("你拒绝了对方的请求.");
					return;
				}
				else
				{
					if(!remoteControl.isUseful())
					{
						//写入cookie，以便安装完成，控件连接上后，可以直接启动 
						setCookie("lastUnFinishedPeerId", peerid);						
						socket.emit("command", {type: eCmd_StartingRemoteControl, peerid:myuserid, peername:"牛魔王", userid:peerid});
						ShowStartOrdownload();
						appendInfo("请根据提示启动或安装远程组件.");
						return;
					}
				}
				socket.emit("command", {type: eCmd_AnswerControlRequest, peerid:myuserid, userid:peerid});	
				
				var ret = remoteControl.InitRemote($("#myid").val(), peerid, "孙悟空", "牛魔王");
				if(ret == emcontrolSuccess)
				{	
					clearInterval(checkStatusInterval);			
					checkStatusInterval = setInterval("GetStatus();", 1000);
				}
				remoteControl.StartControl(0, 0, 0);								
				appendInfo("正在启动远程服务.");
				remotingPeerId = msg.peerid;
				startOrStopCheckLoop(true);
			}
			break;
			case eCmd_AnswerControlRequest:
			{
				var peerid = msg.peerid;
				var ret = remoteControl.InitRemote($("#myid").val(), peerid, "孙悟空", "牛魔王");
				if(ret == emcontrolSuccess)
				{					
					clearInterval(checkStatusInterval);			
					checkStatusInterval = setInterval("GetStatus();", 1000);
				}
				remoteControl.StartControl(1, 1, 1);
				appendInfo("收到对方响应，正在启动远程，请稍候.");
				remotingPeerId = msg.peerid;
				startOrStopCheckLoop(true);
			}
			break;
			case eCmd_RejectControlRequest:
			{
				appendInfo("对方拒绝了你的请求.");
			}
			break;
			case eCmd_StartedRemoteControl:
			{
				appendInfo("对方控件启动成功.");
			}
			break;
			case eCmd_StartingRemoteControl:
			{
				appendInfo("对方控件正在启动中，启动后会自动接受您的连接，请稍候...");
			}
			break;
			case eCmd_StopControlForLocalFailed:
			{
				appendInfo("对方远程出错，结束远程.");
				remoteControl.DisConnect();
				startOrStopCheckLoop(false);
			}
			break;
			case eCmd_StopControl:
			{
				appendInfo("收到结束指令，退出远程.");
				remoteControl.DisConnect();
				startOrStopCheckLoop(false);
			}
			break;
		}
	});
}
	